﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace Google.Analytics.Web.Converters
{
    public class EnumConverter<T> : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            // We can convert from a string to a IList<Metrics> type
            if (sourceType == typeof(string)) { return true; }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            // If source value is a Hand type
            if (value is T[])
            {
                // Convert to string
                if ((destinationType == typeof(string)))
                {
                    var metrics = (T[])value;
                    var sb = new StringBuilder();
                    foreach (var metric in metrics)
                    {
                        sb.Append(metric + ",");
                    }

                    return (sb.Length>0) ? sb.ToString(0, sb.Length - 1) : string.Empty;
                }
            }
            return base.ConvertTo(context, culture, value, destinationType);

        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            // If converting from a string
            if (value is string)
            {
                // Build IList type
                // Get CSV
                IList<T> metrics = new List<T>();
                var propertyList = (string)value;
                foreach (var c in propertyList.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries))
                {
                    metrics.Add((T) Enum.Parse(typeof (T), c.Trim()));
                }
                return metrics.ToArray();
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override bool GetPropertiesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {
            return TypeDescriptor.GetProperties(value);
        }


    }
}